package cn.tom.tool;

import cn.tom.dao.UserMapper;
import cn.tom.entity.Usr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class Token {
    private static Logger log = LoggerFactory.getLogger("Token");

    @Autowired(required = false)
    UserMapper userDao;
    private static UserMapper userDao2 = null;

    public static String getAccount() {
       /* System.out.println(SecurityContextHolder.getContext().getAuthentication());*/
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("principal==============" + principal);
        if (principal == null) {
            return null;
        }
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return String.valueOf(principal);
    }

    @PostConstruct //添加了就会只运行一次
    public void init() {
        userDao2 = this.userDao;
    }

    public static int getUid() {
        String account = getAccount();
        log.info("account=" + account);
        if (account == null || account.length() < 1) {
            return -1;
        }
        Usr u = userDao2.findByAccount(account);
        log.info("User=" + u);
        if (u == null) {
            return -1;
        }
        return u.getId();
    }

    public static Usr getUser() {
        String account = getAccount();
        if (account == null || account.length() < 1) {
            return null;
        }
        System.out.println("getUser account=" + account);
        return userDao2.findByAccount(account);
    }
}
